package com.deyuanyun.pic.ctrl.app.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.deyuanyun.pic.common.cache.TempStoreDataSupport;
import com.deyuanyun.pic.common.util.CommonUtil;
import com.deyuanyun.pic.common.util.ObjectUtil;
import com.deyuanyun.pic.common.util.StringUtils;
import com.deyuanyun.pic.common.util.web.Asserts;
import com.deyuanyun.pic.ctrl.app.domain.*;
import com.deyuanyun.pic.ctrl.app.domain.Device.*;
import com.deyuanyun.pic.ctrl.app.enumeration.CtrlAppCode;
import com.deyuanyun.pic.ctrl.app.mapper.CtrlMapper;
import com.deyuanyun.pic.ctrl.app.service.CtrlService;
import com.deyuanyun.pic.ctrl.app.service.DeviceService;
import com.deyuanyun.pic.ctrl.domain.*;
import com.deyuanyun.pic.ctrl.enumeration.EqptRunningStatedEnum;
import com.deyuanyun.pic.ctrl.enumeration.EqptTypeEnum;
import com.deyuanyun.pic.ctrl.enumeration.ExceptionHandlingStateEnum;
import com.deyuanyun.pic.ctrl.mapper.*;
import com.deyuanyun.pic.pipe.domain.PipeLineElement;
import com.deyuanyun.pic.pipe.domain.PipeLineElementExample;
import com.deyuanyun.pic.pipe.mapper.PipeLineElementMapper;
import com.deyuanyun.pic.settings.controller.pipe.vo.PipeLocationDTO;
import com.deyuanyun.pic.settings.controller.pipe.vo.PipePositionDTO;
import com.deyuanyun.pic.settings.domain.pipe.PipeLine;
import com.deyuanyun.pic.settings.domain.util.DomainFieldReflectUtil;
import com.deyuanyun.pic.settings.enumeration.UserState;
import com.deyuanyun.pic.settings.service.pipe.PipeLineService;
import com.deyuanyun.pic.settings.service.pipe.PipeLocationService;
import com.deyuanyun.pic.settings.service.pipe.ValveRoomService;
import com.deyuanyun.pic.settings.support.biz.CodeUtil;
import com.deyuanyun.pic.settings.task.StaticConsts;
import org.apache.commons.beanutils.PropertyUtils;
import org.apache.poi.ss.formula.eval.RelationalOperationEval;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.PropertyAccessorUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * @author Jerry
 * @Description 腐蚀控制业务层实现类
 * @date 2016-09-20
 */
@Service
public class CtrlServiceImpl implements CtrlService {

    //——————————————————————————————————————————————————————————————————————--//

    private static final String DOWNREASON = "DOWNREASON";//停机原因

    private static final String APPEARANCECHECK = "APPEARANCE_CHECK";//外观检查（防浪涌）

    private static final String FINESTATUS = "FINE_STATUS";//完好情况（阴保测试桩）

    private static final String MOUNTINGPOSITION = "MOUNTING_POSITION";//安装位置（绝缘装置）

    private static final String INTERFERENCETYPE = "INTERFERENCE_TYPE";//干扰类型（排流装置）

    private static final String CURRENTDRAINAGE = "CURRENT_DRAINAGE";//排流器类型（排流装置）

    public static final int EDIT_ADD = 1;//添加收藏

    public static final int EDIT_CANCEL = 2;//取消收藏

    private enum modeType {
        YES, NO
    }



    @Resource
    private CtrlMapper ctrlMapper;//腐蚀控制mapper

    @Resource
    private RecodeExceptionMapper recodeExceptionMapper;//设备运行记录的异常信息

    @Resource
    private EqptFavoritesMapper eqptFavoritesMapper;//收藏设备mapper

    @Resource
    private PipeFollowMapper pipeFollowMapper;//关注设备和管道

    @Resource
    private DeviceService deviceService;//九大设备service

    @Resource
    private PipeLineService pipeLineService;//管道service;

    @Resource
    private ValveRoomService valveRoomService;//阀室service

    @Resource
    private PipeLocationService pipeLocationService;//管道位置service

    @Resource
    private PipeLineElementMapper pipeLineElementMapper;


    @Override
    public CtrlResult getUserName(String account) {
        Map<String, Object> maps = new HashMap();
        CtrlResult ctrlResult = new CtrlResult();
        List<Map<String, Object>> map = ctrlMapper.login(account);

        if (map.size() == 0) {
            return setPorperty(CtrlAppCode.USER_FAIL.getCode(),
                    CtrlAppCode.USER_FAIL.getLabel(), ctrlResult);
        }

        if (map.size() > 1) {
            return setPorperty(CtrlAppCode.USER_REPEAT.getCode(),
                    CtrlAppCode.USER_REPEAT.getLabel(), ctrlResult);
        }

        Map<String,Object> map1 = map.get(0);
        if(!UserState.ACTIVATE.toString().equals(map1.get("STATE"))){
            return setPorperty(CtrlAppCode.USER_FORBIDDEN.getCode(),
                    CtrlAppCode.USER_FORBIDDEN.getLabel(), ctrlResult);
        }

        ctrlResult.setCode(CtrlAppCode.SUCCESS.getCode());
        ctrlResult.setMsg(CtrlAppCode.SUCCESS.getLabel());
        maps.put("UserName", map1.get("USERNAME"));
        ctrlResult.setResult(maps);
        return ctrlResult;
    }

    private CtrlResult setPorperty(String code, String label, CtrlResult ctrlResult) {
        ctrlResult.setCode(code);
        ctrlResult.setMsg(label);
        return ctrlResult;
    }

    @Override
    public CtrlResult login(String Param, HttpServletRequest request) {
        JSONObject obj = JSON.parseObject(Param);
        int type = obj.getIntValue("Type");
        String account = obj.getString("Account").trim();
        String code = obj.getString("Code");
        // String DeviceID = obj.getString("DeviceID");
        CtrlResult ctrlResult = new CtrlResult();
        Map<String, Object> map = new HashMap<String, Object>();
        List<Map<String, Object>> mapList = ctrlMapper.login(account);

        if (account == null) {
            this.insertLog(Param, mapList, 1);
            return setPorperty(CtrlAppCode.PARAMETER_FAIL.getCode(),
                    CtrlAppCode.PARAMETER_FAIL.getLabel(), ctrlResult);
        }

        if (type == 1) {//此为用户登录
            if (mapList == null) {
                this.insertLog(Param, mapList, 1);
                return setPorperty(CtrlAppCode.USER_FAIL.getCode(),
                        CtrlAppCode.USER_FAIL.getLabel(), ctrlResult);
            }

            if (!code.equals(mapList.get(0).get("PWD"))) {
                this.insertLog(Param, mapList, 1);
                return setPorperty(CtrlAppCode.CODE_FAIL.getCode(),
                        CtrlAppCode.CODE_FAIL.getLabel(), ctrlResult);
            }
            if (code != null && code.equals(mapList.get(0).get("PWD"))) {
                ctrlResult.setCode(CtrlAppCode.SUCCESS.getCode());
                ctrlResult.setMsg(CtrlAppCode.SUCCESS.getLabel());
                String userId = (String) mapList.get(0).get("ID_");
                Map<String, Object> realMap = ctrlMapper.selectRealName(userId);
                if (realMap != null) {
                    String companyId = realMap.get("CPD").toString();
                    map.put("Corp", selectCompanyName(companyId));
                    map.put("PhoneNum", realMap.get("MOBILE"));
                    map.put("RealName", realMap.get("REALNAME"));
                }
                map.put("ID", userId);
                ctrlResult.setResult(map);
                this.insertLog(Param, mapList, 0);
                request.getSession().setAttribute("App_User_", mapList);
            }
            return ctrlResult;
        } else {  //此为手机号登录

            if (StringUtils.isEmpty(code)) {
                return setPorperty(CtrlAppCode.CAPTCHA_NULL.getCode(),
                        CtrlAppCode.CAPTCHA_NULL.getLabel(), ctrlResult);
            }
            String phone = account.trim();
            Asserts.assertTrue(StringUtils.isMobile(phone), "手机号码非法");
            Integer num = TempStoreDataSupport.pullData("ck_capt_" + phone);
            if (num == null) {
                num = 1;
            } else {
                ++num;
            }
            if (num > 5) {
                TempStoreDataSupport.removeData(StaticConsts.PM_LOGIN_CODE + phone);
                return setPorperty(CtrlAppCode.CAPTCHA_FAILMORE.getCode(),
                        CtrlAppCode.CAPTCHA_FAILMORE.getLabel(), ctrlResult);
            }

            String ck = TempStoreDataSupport.pullData(StaticConsts.PM_LOGIN_CODE + phone);
            if (code.equals(ck)) {
                return setPorperty(CtrlAppCode.CAPTCHA_SUCCESS.getCode(),
                        CtrlAppCode.CAPTCHA_SUCCESS.getLabel(), ctrlResult);
            } else {
                TempStoreDataSupport.pushDataByIdelTimeMinute("ck_capt_" + phone, num, StaticConsts.ck_capt_);
                return setPorperty(CtrlAppCode.CAPTCHA_ERROR.getCode(),
                        CtrlAppCode.CAPTCHA_ERROR.getLabel(), ctrlResult);
            }
        }
    }

    /**
     * 通过递归查询一级公司名称
     * @param companyId
     * @return
     */
    private String selectCompanyName(String companyId) {
        Map<String, Object> map = ctrlMapper.selectCompanyName(companyId);
        Object parentId = map.get("PARENTID");
        String realName = map.get("SHORTNAME").toString();
        if (ObjectUtil.isNotNullEmpty(parentId)) {
            selectCompanyName(parentId.toString());
        } else {
            return realName;
        }
        return realName;
    }

    /**
     * 异步写入日志
     *
     * @param Param
     * @param mapList
     * @param type
     */
    private void insertLog(String Param, List<Map<String, Object>> mapList, int type) {
        CtrlLoginLog loginLog = JSON.parseObject(Param, CtrlLoginLog.class);
        loginLog.setId(CommonUtil.getUUID());
        DomainInitUtil.initCreateDomain(loginLog);
        if (ObjectUtil.isNotNullEmpty(mapList)) {
            loginLog.setUserId((String) mapList.get(0).get("ID_"));
        }
        loginLog.setState(type);
        ctrlMapper.insertLog(loginLog);
    }

    @Override
    public void insertErrLog(CtrlLoginLog ctrlLoginLog) {
        ctrlMapper.insertLog(ctrlLoginLog);
    }

    @Override
    public Map getConfigs() {
        Map<String, Object> map = new HashMap<String,Object>();
        EqptRunningStatedEnum rs[] = EqptRunningStatedEnum.values();
        List<Map<String, Object>> mapList = new ArrayList();
        Map<String, Object> cpMap = new HashMap<String,Object>();
        for (int i = 0; i < rs.length; i++) {
            Map<String, Object> map1 = new HashMap<String,Object>();
            map1.put("id", rs[i].toString());
            map1.put("name", rs[i].getLabel());
            mapList.add(map1);
        }
        cpMap.put("List", mapList);
        map.put("CPRunningStatus", cpMap);//阴保运行状态
        map.put("CPHaltCause", CodeUtil.getCtrlAppCodeList(DOWNREASON));//阴保停机原因
        map.put("IDInstallSite", CodeUtil.getCtrlAppCodeList(MOUNTINGPOSITION));//绝缘装置安装位置
        map.put("SPAppearance", CodeUtil.getCtrlAppCodeList(APPEARANCECHECK));//防浪涌保护器外观情况
        map.put("TSStubCondition", CodeUtil.getCtrlAppCodeList(FINESTATUS));//测试桩的电位桩的完好情况
        map.put("DrainageDevice", CodeUtil.getCtrlAppCodeList(CURRENTDRAINAGE));//排流器类型（排流装置）
        map.put("Interference", CodeUtil.getCtrlAppCodeList(INTERFERENCETYPE));//干扰类型（排流装置）
        return map;
    }

    @Override
    public Map getInfrastructures() {
        Map<String, Object> map = new HashMap<String, Object>();
        List<Map<String, Object>> pipeMap = new ArrayList();
        List<Map<String, Object>> roomMap = new ArrayList();
        map.put("CpPowerList", getImportData(deviceService.selectEqptPower()));//阴保电源
        map.put("EqptRefenceList", getImportData(deviceService.selectEqptRefence()));//长效参比电极
        map.put("AnodeList", getImportData(deviceService.selectAnode()));//阳极地床
        map.put("InsluateList", getImportData(deviceService.selectInsluate()));//绝缘装置
        map.put("AntiList", getImportData(deviceService.selectAnti()));//防浪涌保护器
        map.put("CpTestList", getImportData(deviceService.selectCptest()));//测试桩
        map.put("CpJumperList", getImportData(deviceService.selectCpJumper()));//阴极保护跨接线
        map.put("SaalList", getImportData(deviceService.selectSaal()));//牺牲阳极
        map.put("DrainList", getImportData(deviceService.selectDrain()));//排流装置
        List<PipeLine> pipeList = pipeLineService.getLine();
        for (int i = 0; i < pipeList.size(); i++) {
            Map<String, Object> map1 = new HashMap<String,Object>();
            PipeLine pipe = pipeList.get(i);
            map1.put("id", pipe.getId());
            map1.put("name", pipe.getShowName());
            pipeMap.add(map1);
        }
        map.put("PipeList", pipeMap);
        // List<ValveRoom> roomList = valveRoomService.queryAllValueRoomList(new HashMap());
        PipeLineElementExample example = new PipeLineElementExample();
        example.createCriteria().andElementTypeEqualTo("VALVEROOM").andDeletedEqualTo((short) 0);
        List<PipeLineElement> roomList = pipeLineElementMapper.selectByExample(example);
        for (PipeLineElement room : roomList) {
            Map<String, Object> map1 = new HashMap<String,Object>();
            map1.put("id", room.getElementId());
            map1.put("name", room.getElementName());
            map1.put("mileage", room.getMileage());
            map1.put("pipeLineId", room.getPipeLineId());
            roomMap.add(map1);
        }
        map.put("ValveRoomList", roomMap);

        return map;
    }


    private List<BaseDeviceDto> getImportData(List data) {
        Map<String, Object> map = new HashMap<String, Object>();
        List<BaseDeviceDto> result = new ArrayList<BaseDeviceDto>();
        for (int i = 0; i < data.size(); i++) {
            BaseDeviceDto baseDervice = new BaseDeviceDto();
            Object o = data.get(i);
            String jsonString = JSON.toJSONString(o);
            JSONObject jsonObject = JSON.parseObject(jsonString);
            baseDervice.setId(jsonObject.getString("id"));
            baseDervice.setEqptNumber(jsonObject.getString("customNumber"));
            baseDervice.setTestStationId(jsonObject.getString("testStationId"));
            baseDervice.setPipeLineId(jsonObject.getString("pipeLineId"));
            baseDervice.setValveRoomId(jsonObject.getString("pipeValveroomId"));
            //阴保电源居然生成的实体类属性objectname居然不是驼峰命名
            if (o instanceof EqptCppowerr) {
                baseDervice.setObjectName(jsonObject.getString("objectname"));
            } else {
                baseDervice.setObjectName(jsonObject.getString("objectName"));
            }
            baseDervice.setProtectObject(CodeUtil.getName(jsonObject.getString("protectionObject")));
            if (o instanceof EqptCpJumper || o instanceof EqptSaalAnode || o instanceof EqptCurrentDrainage) {
                baseDervice.setMileage(jsonObject.getString("beginMileage"));
            } else {
                baseDervice.setMileage(jsonObject.getString("mileage"));
            }
            baseDervice.setMaterial(jsonObject.getString("material"));
            baseDervice.setPurpose(jsonObject.getString("purpose"));
            baseDervice.setInstallationsite(CodeUtil.getName(jsonObject.getString("installationsite")));
            baseDervice.setCurrentdrainage(jsonObject.getString("currentdrainage"));
            baseDervice.setInterferenceType(CodeUtil.getName(jsonObject.getString("interferenceType")));
            baseDervice.setX(jsonObject.getString("positionX"));
            baseDervice.setX(jsonObject.getString("positionY"));
            result.add(baseDervice);
        }

        return result;
    }

    @Override
    public void postForm(String param) {
        JSONObject obj = JSON.parseObject(param);
        String id = obj.getString("eqptType");//表单类型
        EqptTypeEnum eqptTypeEnum = EqptTypeEnum.valueOf(id);
        String exceptionId = null;
        switch (eqptTypeEnum) {
            case CPPOWER://阴保电源
                exceptionId = insertException(param);
                RecodeCpPowerDto recodeCpPower = JSON.parseObject(param, RecodeCpPowerDto.class);
                DomainInitUtil.initCreateDomain(recodeCpPower);
                recodeCpPower.setExceptionId(exceptionId);
                ctrlMapper.insertCpPower(recodeCpPower);
                break;
            case REFERENCE://长效参比
                exceptionId = insertException(param);
                RecodeReferenceDto recodeReference = JSON.parseObject(param, RecodeReferenceDto.class);
                DomainInitUtil.initCreateDomain(recodeReference);
                recodeReference.setExceptionId(exceptionId);
                ctrlMapper.insertReference(recodeReference);
                break;
            case ANODESBED://辅助阳极地床
                exceptionId = insertException(param);
                RecodeAnodesbedDto recodeAnodesbed = JSON.parseObject(param, RecodeAnodesbedDto.class);
                DomainInitUtil.initCreateDomain(recodeAnodesbed);
                recodeAnodesbed.setExceptionId(exceptionId);
                ctrlMapper.insertAnodesbed(recodeAnodesbed);
                break;
            case INSULATEDJOINT://绝缘装置
                exceptionId = insertException(param);
                RecodeInsedJointDto recodeInsedJoint = JSON.parseObject(param, RecodeInsedJointDto.class);
                DomainInitUtil.initCreateDomain(recodeInsedJoint);
                recodeInsedJoint.setExceptionId(exceptionId);
                ctrlMapper.insertInsedJoint(recodeInsedJoint);
                break;
            case ANTISURGE://防浪涌保护器
                exceptionId = insertException(param);
                RecodeAntiSurgeDto recodeAntiSurge = JSON.parseObject(param, RecodeAntiSurgeDto.class);
                DomainInitUtil.initCreateDomain(recodeAntiSurge);
                recodeAntiSurge.setExceptionId(exceptionId);
                ctrlMapper.insertAntiSurge(recodeAntiSurge);
                break;
            case CPJUMPER://阴极保护跨接线
                exceptionId = insertException(param);
                RecodeCpJumperDto recodeCpJumper = JSON.parseObject(param, RecodeCpJumperDto.class);
                DomainInitUtil.initCreateDomain(recodeCpJumper);
                recodeCpJumper.setExceptionId(exceptionId);
                ctrlMapper.insertCpJumper(recodeCpJumper);
                break;
            case CPTESTSTATION://阴保测试桩
                exceptionId = insertException(param);
                RecodeCpTestStationDto recodeCpTestStation = JSON.parseObject(param, RecodeCpTestStationDto.class);
                DomainInitUtil.initCreateDomain(recodeCpTestStation);
                recodeCpTestStation.setExceptionId(exceptionId);
                ctrlMapper.insertCpTestStation(recodeCpTestStation);
                break;
            case SAALANODE://牺牲阳极
                exceptionId = insertException(param);
                RecodeSaalAnodeDto recodeSaalAnode = JSON.parseObject(param, RecodeSaalAnodeDto.class);
                DomainInitUtil.initCreateDomain(recodeSaalAnode);
                recodeSaalAnode.setExceptionId(exceptionId);
                ctrlMapper.insertSaalAnode(recodeSaalAnode);
                break;
            case CURRENTDRAINAGE://排流装置
                exceptionId = insertException(param);
                RecodeDrainageDto recodeDrainage = JSON.parseObject(param, RecodeDrainageDto.class);
                DomainInitUtil.initCreateDomain(recodeDrainage);
                recodeDrainage.setExceptionId(exceptionId);
                ctrlMapper.insertDrainage(recodeDrainage);
                break;
        }

    }

    /**
     * 根据逻辑往异常表里面注入信息
     *
     * @param param
     * @return
     */
    private String insertException(String param) {
        JSONObject obj = JSON.parseObject(param);
        int mode = obj.getIntValue("mode");

        RecodeExceptionDto recodeException = JSON.parseObject(param, RecodeExceptionDto.class);
        if (1 == mode) {
            recodeException.setType(modeType.NO.name());
        } else {
            recodeException.setType(modeType.YES.name());
        }
        String exceptionId = CommonUtil.getUUID();
        String recodeId = recodeException.getId();
        recodeException.setCreateDate(new Date());
        recodeException.setId(exceptionId);
        recodeException.setRecodeId(recodeId);
        recodeException.setStated(ExceptionHandlingStateEnum.UNTREATED.toString());

        String description = recodeException.getDescription();
        RecodeException recodeException1 = new RecodeException();
        BeanUtils.copyProperties(recodeException, recodeException1);
        if (description != null) {//有异常记录才往异常记录表注入信息
            recodeExceptionMapper.insertSelective(recodeException1);
            return exceptionId;
        }
        return null;
    }


    @Override
    public void reportException(String Param) {
        RecodeException recodeException = JSON.parseObject(Param, RecodeException.class);
        recodeExceptionMapper.insert(recodeException);
    }

    @Override
    public PipefromToDto queryPipeFromToById(String Param) {
        JSONObject obj = JSON.parseObject(Param);
        String pipeLineId = obj.getString("pipeLineId");
        //String pipeLineId = "4c3fb109c9d944f6a2f23ef4e6dcecfc";
        PipePositionDTO pipePosition = pipeLocationService.queryPipeLinePosition(pipeLineId);
        PipefromToDto fromTo = new PipefromToDto();
        BeanUtils.copyProperties(pipePosition, fromTo);
        return fromTo;
    }

    @Override
    public Map queryPipePlaceByName(String Param) {
        Map map = new HashMap();
        JSONObject obj = JSON.parseObject(Param);
        String pipeLineId = obj.getString("pipeLineId");
        String signName = obj.getString("name");
        if (StringUtils.isEmpty(signName)) {
            return null;
        }
        List<PipePlaceDto> list1 = new ArrayList<PipePlaceDto>();
        List<PipeLocationDTO> list = pipeLocationService.queryPipeLocation(pipeLineId, null, null, signName, null);
        //BeanUtils.copyProperties(list, list1);
        for (PipeLocationDTO pipeLocation : list) {
            PipePlaceDto pipePlace = new PipePlaceDto();
            pipePlace.setId(pipeLocation.getId());
            pipePlace.setName(pipeLocation.getName());
            pipePlace.setMileage(pipeLocation.getMileage());
            list1.add(pipePlace);
        }
        if (ObjectUtil.isNotNullEmpty(list1)) {
            map.put("List", list1);
        }

        return map;
    }

    @Override
    public void settingPlan(String Param) {
        FollowDerviceDto followDevice = JSON.parseObject(Param, FollowDerviceDto.class);

        //如果有记录进行删除
        String userId = followDevice.getUserID();
        PipeFollowExample example = new PipeFollowExample();
        example.createCriteria().andCreateUserEqualTo(userId).andDeletedEqualTo((short) 0);
        List<PipeFollow> pipeFollowList = pipeFollowMapper.selectByExample(example);
        if (ObjectUtil.isNotNullEmpty(pipeFollowList) && ObjectUtil.isNotNullEmpty(followDevice.getFollowDevice())) {
            PipeFollow follow = new PipeFollow();
            follow.setDeleted((short) 1);
            follow.setUserId(userId);
            ctrlMapper.updateFollow(follow);
        }


        String[] commDevice = followDevice.getFollowDevice().getCommonDevices();
        if (commDevice != null) {
            for (int i = 0; i < commDevice.length; i++) {
                insertFollow(commDevice[i], null, followDevice);
            }
        }

        String[] pipeDevice = followDevice.getFollowDevice().getPipeDevices();
        if (pipeDevice != null) {
            for (int i = 0; i < pipeDevice.length; i++) {
                insertFollow(pipeDevice[i], null, followDevice);
            }
        }

        PipeSection[] pipes = followDevice.getFollowDevice().getPipes();
        if (pipes != null) {
            for (int i = 0; i < pipes.length; i++) {
                insertFollow(null, pipes[i], followDevice);
            }
        }

    }

    private void insertFollow(String deviceType, PipeSection pipeSection, FollowDerviceDto followDerviceDto) {
        PipeFollow pipeFollow = new PipeFollow();
        pipeFollow.setId(CommonUtil.getUUID());
        pipeFollow.setCreateDate(new Date());
        pipeFollow.setCreateUser(followDerviceDto.getUserID());
        pipeFollow.setUserId(followDerviceDto.getUserID());
        pipeFollow.setEqptType(deviceType);
        if (ObjectUtil.isNotNullEmpty(pipeSection)) {
            pipeFollow.setPipeLineId(pipeSection.getPipeLineId());

            if (ObjectUtil.isNotNullEmpty(pipeSection.getFromPoint())) {
                pipeFollow.setBeginId(pipeSection.getFromPoint().getId());
                pipeFollow.setBeginName(pipeSection.getFromPoint().getName());
                pipeFollow.setBeginMileage(pipeSection.getFromPoint().getMileage());
            }
            if (ObjectUtil.isNotNullEmpty(pipeSection.getToPoint())) {
                pipeFollow.setEndId(pipeSection.getToPoint().getId());
                pipeFollow.setEndName(pipeSection.getToPoint().getName());
                pipeFollow.setEndMileage(pipeSection.getToPoint().getMileage());
            }
        }
        pipeFollowMapper.insertSelective(pipeFollow);
    }


    @Override
    public Map getPlanSetting(String Param) {
        Map map1 = new HashMap();
        Map map = new HashMap();
        List<PipeSection> pipeSection = new ArrayList<PipeSection>();
        List<String> commonDevices = new ArrayList<String>();
        List<String> pipeDevices = new ArrayList<String>();
        JSONObject obj = JSON.parseObject(Param);
        String userId = obj.getString("userID");
        PipeFollowExample example = new PipeFollowExample();
        example.createCriteria().andCreateUserEqualTo(userId).andDeletedEqualTo((short) 0);
        List<PipeFollow> pipeFollowList = pipeFollowMapper.selectByExample(example);
        for (PipeFollow pipeFollow : pipeFollowList) {
            String eqptType = pipeFollow.getEqptType();
            if (EqptTypeEnum.CPPOWER.toString().equals(eqptType) || EqptTypeEnum.ANODESBED.toString().equals(eqptType)) {
                commonDevices.add(eqptType);
            } else if (eqptType != null) {
                pipeDevices.add(eqptType);
            }
            if (StringUtils.isNotEmpty(pipeFollow.getPipeLineId())) {
                PipeSection section = new PipeSection();
                section.setPipeLineId(pipeFollow.getPipeLineId());

                PipePoint fromPoint = new PipePoint();
                fromPoint.setId(pipeFollow.getBeginId());
                fromPoint.setName(pipeFollow.getBeginName());
                fromPoint.setMileage(pipeFollow.getBeginMileage());
                section.setFromPoint(fromPoint);

                PipePoint toPoint = new PipePoint();
                toPoint.setId(pipeFollow.getEndId());
                toPoint.setName(pipeFollow.getEndName());
                toPoint.setMileage(pipeFollow.getEndMileage());
                section.setToPoint(toPoint);

                pipeSection.add(section);
            }
        }
        map.put("commonDevices", commonDevices);
        map.put("pipeDevices", pipeDevices);
        map.put("pipes", pipeSection);

        if (ObjectUtil.isNotNullEmpty(map)) {
            map1.put("followDevice", map);
        }
        return map1;
    }

    @Override
    public void updateFavourites(String Param) {
        insertFavourite(Param);
    }

    @Override
    public Map getFavourites(String Param) {
        JSONObject obj = JSON.parseObject(Param);
        String userId = obj.getString("userID");
        List<Map> list = new ArrayList<Map>();
        Map<String, Object> map = new HashMap<String, Object>();
        EqptFavoritesExample example = new EqptFavoritesExample();
        example.createCriteria().andUserIdEqualTo(userId).andDeletedEqualTo((short) 0);
        List<EqptFavorites> eqptFavoritesList = eqptFavoritesMapper.selectByExample(example);
        for (int i = 0; i < eqptFavoritesList.size(); i++) {
            Map<String, Object> map1 = new HashMap<String, Object>();
            EqptFavorites eqptFavorites = eqptFavoritesList.get(i);
            map1.put("eqptId", eqptFavorites.getEqptId());
            map1.put("eqptType", eqptFavorites.getEqptType());
            list.add(map1);
        }
        if (ObjectUtil.isNotNullEmpty(list)) {
            map.put("List", list);
        }

        return map;
    }

    @Override
    public void editFavourites(String Param) {
        JSONObject obj = JSON.parseObject(Param);
        int editType = obj.getIntValue("editType");
        if (EDIT_ADD == editType) {
            insertFavourite(Param);
        } else if (EDIT_CANCEL == editType) {
            EqptFavorites eqptFavorites = new EqptFavorites();
            String eqptId = obj.getString("eqptId");
            eqptFavorites.setEqptId(eqptId);
            eqptFavorites.setDeleted((short) 1);
            ctrlMapper.updateFavouriteByEqptId(eqptFavorites);
        }
    }

    /**
     * 添加收藏
     *
     * @param Param
     */
    public void insertFavourite(String Param) {
        JSONObject obj = JSON.parseObject(Param);
        String eqptId = obj.getString("eqptId");
        String eqptType = obj.getString("eqptType");
        String userId = obj.getString("userID");
        EqptFavorites eqptFavorites = new EqptFavorites();
        eqptFavorites.setId(CommonUtil.getUUID());
        eqptFavorites.setCreateDate(new Date());
        eqptFavorites.setCreateUser(userId);
        eqptFavorites.setUserId(userId);
        eqptFavorites.setEqptId(eqptId);
        eqptFavorites.setEqptType(eqptType);
        eqptFavoritesMapper.insertSelective(eqptFavorites);
    }


    /**
     * 封装发送消息函数
     *
     * @param ctrlResult 对象
     * @param code       code编码
     * @param label      对应消息
     */
    private CtrlResult addCodeMsg(CtrlResult ctrlResult, String code, String label) {

        ctrlResult.setCode(code);
        ctrlResult.setMsg(label);
        return ctrlResult;

    }


}


class DomainInitUtil {

    /**
     * 初始化domain其中的createDate、id(UUID)
     *
     * @param domainObj
     * @return
     */
    public static void initCreateDomain(Object domainObj) {
        initCreateDomain(domainObj, null);
    }

    public static void initCreateDomain(Object domainObj, String remark) {

        //  DomainFieldReflectUtil.setFieldValue(domainObj, "id", CommonUtil.getUUID());
        DomainFieldReflectUtil.setFieldValue(domainObj, "createDate", new Date());
        if (StringUtils.isNotEmpty(remark)) {
            DomainFieldReflectUtil.setFieldValue(domainObj, "createRemark", remark);
        }

    }

    /**
     * 初始化domain其中的updateDate、updateUser
     *
     * @param domainObj
     * @return
     */
    public static void initUpdateDomain(Object domainObj) {
        initUpdateDomain(domainObj, null);
    }


    /**
     * 初始化domain其中的updateDate、updateUser、updateRemark
     *
     * @param domainObj
     * @param remark
     */
    public static void initUpdateDomain(Object domainObj, String remark) {

//        UserSessionVO sessionVO= SessionCacheSupport.getSessionVO();
//        String userid = sessionVO.getId();

        DomainFieldReflectUtil.setFieldValue(domainObj, "updateDate", new Date());
        if (StringUtils.isNotEmpty(remark)) {
            DomainFieldReflectUtil.setFieldValue(domainObj, "updateRemark", remark);
        }

    }


}


